﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;

namespace FMSpaceShooter.Data
{
    public sealed class ConfigFile
    {
        private const string fileName = "app.config";
        private DataContractSerializer serializer = new DataContractSerializer(typeof(Options), new List<Type> {  });
        private static readonly Lazy<ConfigFile> _instance = new Lazy<ConfigFile>(() => new ConfigFile());
        private Options _options;

        public Options Options { get { return _options; } }
        public static ConfigFile Instance { get { return _instance.Value; } }

        private ConfigFile()
        {
            if (File.Exists(fileName))
            {
                using (var file = new FileStream(fileName, FileMode.Open))
                {
                    _options = (Options)serializer.ReadObject(file);
                }
            }
            else
            {
                _options = new Options();
            }
        }

        public bool SaveConfig()
        {
            try
            {
                using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    serializer.WriteObject(writer, _options);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
 
}
